package com.liguang.rcs.admin.web.drivermgr;

import com.google.common.base.Strings;
import com.liguang.rcs.admin.exception.BaseException;
import com.liguang.rcs.admin.permission.RequiresPermissionsDesc;
import com.liguang.rcs.admin.service.DriverMgrService;
import com.liguang.rcs.admin.util.response.PageableBody;
import com.liguang.rcs.admin.util.response.ResponseObject;
import com.liguang.rcs.admin.validator.Order;
import com.liguang.rcs.admin.validator.Sort;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/drivermgr")
@Slf4j
public class DriverManagerController {

    @Autowired
    private DriverMgrService driverMgrService;

    @RequiresPermissions("admin:drivermgr:list")
    @RequiresPermissionsDesc(menu={"司机管理", "司机列表"}, button="查询")
    @GetMapping("/list")
    public ResponseObject<PageableBody<DriverVO>> queryPage(String name, String startTime, String endTime,
                                                            @RequestParam(defaultValue = "1") Integer page,
                                                            @RequestParam(defaultValue = "10") Integer limit,
                                                            @Sort @RequestParam(defaultValue = "createDate") String sort,
                                                            @Order @RequestParam(defaultValue = "desc") String order) {
        try {
            return ResponseObject.success(driverMgrService.queryPage(name,
                    formatStartTime(startTime), formatEndTime(endTime), page, limit, sort, order));
        } catch (Exception ex) {
            log.error("queryPage fail, Exception:", ex);
            return ResponseObject.serious();
        }

    }


    @RequiresPermissions("admin:drivermgr:update")
    @RequiresPermissionsDesc(menu={"司机管理", "司机列表"}, button="编辑")
    @PostMapping("/update")
    public ResponseObject update(@Valid @RequestBody DriverVO driverVO) {
        if (driverVO.getId() == null || driverVO.getId() == 0) {
            return ResponseObject.badArgumentValue("ID 编码不可为空");
        }
        try {
            driverMgrService.update(driverVO);
            return ResponseObject.success();
        } catch (BaseException ex) {
            log.error("update fail, Exception:", ex);
            return ResponseObject.fail(ex.getCode(), ex.getMessage());

        } catch (Exception ex) {
            log.error("update fail, Exception:", ex);
            return ResponseObject.serious();
        }
    }


    @RequiresPermissions("admin:drivermgr:create")
    @RequiresPermissionsDesc(menu={"司机管理", "司机列表"}, button="添加")
    @PostMapping("/create")
    public ResponseObject create(@Valid @RequestBody DriverVO driverVO) {
        if (driverVO.getId() != null) {
            return ResponseObject.badArgumentValue("ID 编码必须为空");
        }

        try {
            driverMgrService.add(driverVO);
            return ResponseObject.success();
        }  catch (Exception ex) {
            log.error("create fail, Exception:", ex);
            return ResponseObject.serious();
        }
    }

    @RequiresPermissions("admin:drivermgr:delete")
    @RequiresPermissionsDesc(menu={"司机管理", "司机列表"}, button="删除")
    @DeleteMapping("/delete")
    public ResponseObject delete(@RequestParam(value = "id") Long id) {
        if (id == null || id ==0) {
            return ResponseObject.badArgumentValue("ID 编码不可为空");
        }
        try {
            driverMgrService.delete(id);
            return ResponseObject.success();
        }  catch (Exception ex) {
            log.error("delete fail, Exception:", ex);
            return ResponseObject.serious();
        }
    }

    @RequiresPermissions({"admin:drivermgr:list"})
    @GetMapping("/queryCompany")
    public ResponseObject<List<Map<String, String>>> queryAllCompany() {
        try {
            List<String> companys = driverMgrService.queryAllCompany();
            if (companys != null && !companys.isEmpty()) {
                return ResponseObject.success(companys.stream()
                        .map(company -> {
                            Map<String, String> map = new HashMap<>();
                            map.put("value", company);
                            return map;
                        }).collect(Collectors.toList()));
            }
            return ResponseObject.success();
        } catch (Exception ex) {
            log.error("queryAllCompany, Exception:", ex);
            return ResponseObject.success();
        }
    }
    @RequiresPermissions({"admin:drivermgr:list"})
    @GetMapping("/queryByIdCard")
    public ResponseObject<DriverVO> queryByIdCard(@RequestParam String idCard) {
        try {
            DriverVO driver = driverMgrService.queryByIdCard(idCard);
            if (driver == null) {
                return ResponseObject.dataNotExist();
            }
            return ResponseObject.success(driver);
        } catch (Exception ex) {
            log.error("queryByIdCard fail, Exception:", ex);
            return ResponseObject.serious();
        }
    }

    @RequiresPermissions({"admin:drivermgr:list"})
    @PostMapping("/downloadExcel")
    public void downloadExcel(HttpServletResponse response, String name, String startTime, String endTime) {
        try {
            Workbook wb = driverMgrService.generateWorkbook(name, formatStartTime(startTime), formatEndTime(endTime));
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=template.xlsx");
            response.setHeader("Access-Control-Allow-Origin", "*");
            OutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
                wb.write(response.getOutputStream());
            } finally {
                wb.close();
                outputStream.flush();
                outputStream.close();
            }

        } catch (Exception ex) {
            log.error("downloadExcel fail, Exception:", ex);
        }
    }

    private Date formatStartTime(String startTime) throws Exception {
        if (!Strings.isNullOrEmpty(startTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            return sdf.parse(startTime);
        }
        return null;
    }

    private Date formatEndTime(String endTime) throws Exception {
        if (!Strings.isNullOrEmpty(endTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            Date endDate = sdf.parse(endTime);
            Calendar instance = Calendar.getInstance();
            instance.setTime(endDate);
            instance.add(Calendar.DATE, 1);
            return instance.getTime();
        }
        return null;
    }

}
